package kz.vokebuz.dataStore;

import java.util.ArrayList;
import java.util.List;

import kz.vokebuz.PopUpActivity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsMessage;
import android.util.Log;

public class DataService extends Service {
	private static final String TAG = DataService.class.getSimpleName();

	public static String BROADCAST = "kz.vokebuz.test.UPDLIST";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(TAG, "Service is created - ");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "Service is destroyed - ");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Log.d(TAG, "Service is started - ");

		doConfigureMessage(intent);

	}

	private void writeToSqlite(List<SmsMmsMsg> messages, Context thisContext) {
		DbAdapter dbAdapter = new DbAdapter(thisContext);
		dbAdapter.open();
		int count = messages.size();
		for (int i = 0; i < count; i++) {
			long restl = dbAdapter.addRow(messages.get(i));
			if (restl != 0) {
				Log.d(TAG, "Db wirted  - " + restl);
			} else {
				Log.d(TAG, "Db wirte filed");
			}
		}
		dbAdapter.close();
		sendDBChangeBroadcast(thisContext);

	}

	private void sendDBChangeBroadcast(Context c) {
		Intent intent = new Intent();
		intent.setAction(BROADCAST);
		c.sendBroadcast(intent);

	}

	private void doConfigureMessage(Intent intent) {

		SmsMessage[] msgs = null;
		if (intent.getExtras().containsKey("pdus")) {
			Object[] pdus = (Object[]) intent.getExtras().get("pdus");
			if (pdus != null) {
				List<SmsMmsMsg> messages = null;
				int len = pdus.length;
				msgs = new SmsMessage[len];
				for (int i = 0; i < len; i++) {
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}

			    	messages = new ArrayList<SmsMmsMsg>();
				    SmsMmsMsg msg = new SmsMmsMsg();
				    String lastOriginator = null;

				for (int i = 0; i < msgs.length; i++) {
					msg.setMessageBody(msgs[i].getMessageBody());
					msg.setMsgType(0); // Sms type ;
					lastOriginator = msgs[i].getDisplayOriginatingAddress();
					msg.setTimeStamp(msgs[i].getTimestampMillis());
					msg.setStatusReport(msgs[i].isStatusReportMessage());
					messages.add(msg);
				}
				writeToSqlite(messages, this.getApplicationContext());
			}

		}
		onDestroy();
	}
}
